package com.dmbjz.service;


import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.dmbjz.config.RabbitConfig;
import com.dmbjz.dao.OrderDetailDao;
import com.dmbjz.entity.dto.OrderMessageDTO;
import com.dmbjz.enummeration.OrderStatus;
import com.dmbjz.entity.po.OrderDetailPo;
import com.dmbjz.entity.vo.OrderCreateVo;
import com.dmbjz.moddymq.sender.TransMessageSender;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

/* 订单请求Service */
@Service
public class OrderService {

    @Autowired
    private OrderDetailDao orderDetailDao;
    @Autowired
    private TransMessageSender messageSender;

    /* 创建订单 */
    public void createOrder(OrderCreateVo orderCreateVo) {

        /* 订单数据入库 */
        //1、新增订单
        OrderDetailPo orderDetailPo = new OrderDetailPo();
        orderDetailPo.setAddress(orderCreateVo.getAddress());
        orderDetailPo.setAccountId(orderCreateVo.getAccountId());
        orderDetailPo.setProductId(orderCreateVo.getProductId());
        orderDetailPo.setStatus(OrderStatus.ORDER_CREATEING);
        orderDetailPo.setDate(LocalDateTime.now());
        orderDetailPo.setId(IdUtil.randomUUID());
        orderDetailDao.save(orderDetailPo);

        /* 封装订单消息，发送给餐厅交换机 */
        //2、开始订单的异步过程
        OrderMessageDTO messageDTO = new OrderMessageDTO();
        messageDTO.setOrderID(orderDetailPo.getId());
        messageDTO.setProductId(orderDetailPo.getProductId());
        messageDTO.setAccountId(orderDetailPo.getAccountId());

        String json = JSON.toJSONString(messageDTO);
        MessageProperties properties = new MessageProperties();
        properties.setContentType(MessageProperties.CONTENT_TYPE_JSON);
        properties.setMessageId(messageDTO.getOrderID());
        Message message = new Message(json.getBytes(StandardCharsets.UTF_8), properties);        //指定为JSON格式消息

        //3、发送给餐厅交换机  这里用的封装方法，发送的同时，存进消息事务表里面
        messageSender.send(RabbitConfig.RESTAURANT_EXCHANGE, "key.restaurant", message);

    }


}
